import os
import re
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinterdnd2 import DND_FILES, TkinterDnD

def process_text(text):
    """
    处理字幕文本，过滤序号、时间戳和空行。
    """
    lines = text.splitlines()
    filtered = []
    # 支持 1-2位时分秒 + 1-3位毫秒
    timestamp_pattern = re.compile(
        r'^\d{1,2}:\d{1,2}:\d{1,2},\d{1,3} --> \d{1,2}:\d{1,2}:\d{1,2},\d{1,3}$'
    )
    for line in lines:
        stripped_line = line.strip()
        if re.match(r'^\d+$', stripped_line):  # 序号行
            continue
        elif timestamp_pattern.match(stripped_line):  # 时间戳行
            continue
        elif re.match(r'^\s*$', stripped_line):  # 空行
            continue
        else:
            filtered.append(line)
    return '\n'.join(filtered)

def process_srt_file(srt_file):
    base_name = os.path.splitext(srt_file)[0]
    txt_file = f"{base_name}.txt"
    print(f"正在处理: {srt_file}")
    try:
        with open(srt_file, 'r', encoding='utf-8-sig') as f:
            content = f.read()
    except Exception as e:
        print(f"读取文件 {srt_file} 出错: {e}")
        return
    processed = process_text(content)
    try:
        with open(txt_file, 'w', encoding='utf-8') as f:
            f.write(processed)
        print(f"已保存为: {txt_file}")
    except Exception as e:
        print(f"写入文件 {txt_file} 出错: {e}")

def add_file_to_list(file_path):
    file_listbox.insert(tk.END, file_path)

def convert_files():
    selected_files = file_listbox.get(0, tk.END)
    if not selected_files:
        messagebox.showinfo("提示", "请先拖动 .srt 文件到窗口中。")
        return
    for file_path in selected_files:
        process_srt_file(file_path)
    messagebox.showinfo("提示", "转换完成。")

def on_drop(event):
    file_paths = root.tk.splitlist(event.data)
    for file_path in file_paths:
        if file_path.endswith('.srt'):
            add_file_to_list(file_path)

# 创建主窗口
root = TkinterDnD.Tk()
root.title("SRT 字幕转换器")
root.geometry("600x500")  # 增加窗口高度

# 创建文件列表框
file_listbox = tk.Listbox(root, width=80, height=15)
file_listbox.pack(pady=10)

# 创建拖放区域
drop_label = tk.Label(root, text="将 .srt 文件拖动到此处", bg="lightgrey", width=80, height=5)
drop_label.pack(pady=15)
drop_label.drop_target_register(DND_FILES)
drop_label.dnd_bind('<<Drop>>', on_drop)

# 创建转换按钮
convert_button = tk.Button(
    root,
    text="转换",
    command=convert_files,
    width=20,
    height=2,
    padx=10,
    pady=5
)
convert_button.pack(pady=20)  # 增加按钮与上部组件的距离

# 运行主循环
root.mainloop()